package com.tvunetworks.center.device.service.impl;


import com.tvunetworks.center.common.model.SendMsgToMsgpipeParam;
import com.tvunetworks.center.common.model.anywhere.AnywhereControlMsg;
import com.tvunetworks.center.common.model.anywhere.AnywhereMsgDataType;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.device.service.AnywhereControlService;
import com.tvunetworks.center.device.service.feign.MsgpipeFeignService;
import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.channels.NotYetConnectedException;
import java.security.InvalidParameterException;
/**
 * @program: tvucc-device
 * @description:
 * @author lebronchen
 * @create: 2019-03-19 14:17
 **/
@Slf4j
@Service
public class AnywhereControlServiceImpl implements AnywhereControlService {
	//@Value("${anywhereCropInMemcache}")//todo add to config anywhere_send_crop_message_in_memcache_
	@Value("anywhere_send_crop_message_in_memcache_")
	private String anywhereCropInMemcache;

	@Autowired
	private MsgpipeFeignService msgpipeFeignService;
	@Autowired
	@Qualifier("ccMemcacheClient")
	private MemcachedClient ccMemcachedClient;
	@Override
	public void focusControlMsg(String recipient, int[] parameter) throws NotYetConnectedException, InvalidParameterException {
		if(parameter != null && parameter.length == 2) {
			// 0<=x<=160, 0<=y<=90
			// if(parameter[0] <= MAX_LENGTH && parameter[0] >= MIN_VALUE && parameter[1] <= MAX_WIDTH && parameter[1] >= MIN_VALUE) {
			if(parameter[0] >= MIN_VALUE && parameter[1] >= MIN_VALUE) {
				AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.FOCUS, parameter, null);
				sendAnywhereControlMsg(recipient,msg);
			} else {
				throw new InvalidParameterException();
			}
		} else {
			throw new InvalidParameterException();
		}
	}

	@Override
	public void zoomControlMsg(String recipient, int[] parameter) throws NotYetConnectedException, InvalidParameterException {
		if(parameter != null && parameter.length ==1) {
			// 0<=level<=100
			if(parameter[0] <= MAX_ZOOM && parameter[0] >= MIN_VALUE) {
				AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.ZOOM, null, parameter);
				sendAnywhereControlMsg(recipient, msg);
			} else {
				throw new InvalidParameterException();
			}
		} else {
			throw new InvalidParameterException();
		}
	}

	@Override
	public void exposureControlMsg(String recipient, int[] parameter) throws NotYetConnectedException, InvalidParameterException {
		if(parameter != null && parameter.length == 1) {
			// -50<=level<=50
			if(parameter[0] <= MAX_EXPOSURE && parameter[0] >= MIN_EXPOSURE) {
				AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.EXPOSURE, null, parameter);
				sendAnywhereControlMsg(recipient, msg);
			} else {
				throw new InvalidParameterException();
			}
		} else {
			throw new InvalidParameterException();
		}
	}

	@Override
	public void cropControlMsg(String recipient, int[] parameter) throws NotYetConnectedException, InvalidParameterException {
		if(parameter != null && parameter.length == 2) {
			// 0<=x<=160, 0<=y<=90
			if(parameter[0] >= MIN_VALUE && parameter[1] >= MIN_VALUE) {
			// if(parameter[0] <= MAX_LENGTH && parameter[0] >= MIN_VALUE && parameter[1] <= MAX_WIDTH && parameter[1] >= MIN_VALUE) {
				AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.CROP, parameter, null);
				sendAnywhereControlMsg(recipient, msg);
			} else {
				throw new InvalidParameterException();
			}
		} else {
			throw new InvalidParameterException();
		}
	}
	
	@Override
	public String toggelCropStatus(String recipient, int[] parameter) throws InvalidParameterException {
		if(parameter != null && parameter.length == 1) {
			AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.TOGGLECROP, parameter[0]);
			sendAnywhereControlMsg(recipient, msg); // send message to msgpipe
			String result = getAnywhereBackMessage(recipient, 80L, 2000L); // and wait to get return message or expired
			if(result != null && !"".equals(result)) {
				return result;
			}
		} else {
			throw new InvalidParameterException();
		}
		return null;
	}
	
	@Override
	public void toggleCropStatus(String recipient, int[] parameter) throws InvalidParameterException {
		if(parameter != null && parameter.length == 1) {
			AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.TOGGLECROP, parameter[0]);
			sendAnywhereControlMsg(recipient, msg); // send message to msgpipe
		} else {
			throw new InvalidParameterException();
		}
	}
	
	@Override
	public void resetAllEffect(String recipient) throws NotYetConnectedException {
		if(recipient != null && !"".equals(recipient)) {
			AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.RESET);
			sendAnywhereControlMsg(recipient, msg); // send message to msgpipe
		} else {
			throw new InvalidParameterException();
		}
	}
	
	@Override
	public String getDeviceResolution(String recipient) throws NotYetConnectedException {
		if(recipient != null && !"".equals(recipient)) {
			AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.RESOLUTION);
			sendAnywhereControlMsg(recipient, msg); // send message to msgpipe
			String result = getAnywhereBackMessage(recipient, 80L, 2000L); // and wait to get return message or expired
			if(result != null && !"".equals(result)) {
				return result;
			}
		} else {
			throw new InvalidParameterException();
		}
		return null;
	}
	
	@Override
	public void queryDeviceResolution(String recipient) throws NotYetConnectedException {
		if(recipient != null && !"".equals(recipient)) {
			AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.RESOLUTION);
			sendAnywhereControlMsg(recipient, msg); // send message to msgpipe
		} else {
			throw new InvalidParameterException();
		}
	}


	@Override
	public void isAuto(String recipient, int[] parameter) throws NotYetConnectedException {
		if(parameter != null && parameter.length == 1) {
			AnywhereControlMsg msg = new AnywhereControlMsg(AnywhereMsgDataType.ISAUTO, parameter[0]);
			sendAnywhereControlMsg(recipient, msg); // send message to msgpipe
		} else {
			throw new InvalidParameterException();
		}
		
	}

	/**
	 *
	 * @param recipient recipient
	 * @param msg msg
	 */
	public void sendAnywhereControlMsg(String recipient, AnywhereControlMsg msg){
		if (recipient != null && msg != null) {

			try {
				String msgbody = JsonUtil.toJsonStr(msg);
				if (msgbody == null) {
					return;
				}
				SendMsgToMsgpipeParam param = new SendMsgToMsgpipeParam();
				param.setMsgBody(msgbody);
				param.setType(53);
				param.setBooking(false);
				param.setReceiver(recipient);
				msgpipeFeignService.sendMsgToMsgpipe(param);
			} catch (IOException e) {
				log.error("sendAnywhereControlMsg Exception",e);
			}
		}
	}

	/**
	 *
	 * @param peerId peerId
	 * @param interval interval
	 * @param expiredTime expiredTime
	 * @return String
	 */
	public String getAnywhereBackMessage(String peerId, long interval, long expiredTime) {
		String result = null;
		if (peerId != null && interval > 0L && expiredTime >= interval) {
			while (expiredTime > 0) {
				expiredTime = expiredTime - interval;
				try {
					result = (String) ccMemcachedClient.get(anywhereCropInMemcache + peerId);
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
				if (result == null) {
					try {
						Thread.sleep(interval);
					} catch (InterruptedException e) {
						log.error(e.getMessage(), e);
					}
				} else {
					break;
				}
			}
		}
		return result;
	}

}
